package top.yeyusmile.common;

import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import top.yeyusmile.MainApp;
import top.yeyusmile.utils.HttpUtil;
import top.yeyusmile.utils.MyQQUtil;

import javax.annotation.PostConstruct;
import java.beans.Transient;
import java.io.*;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * @author 夜雨
 * @Web www.yeyusmile.top
 * @date 2022/3/17 8:05
 */
@Slf4j
@Component
@ConfigurationProperties("yeyu")
public class RobotConfig {

    @Autowired
    private transient RobotConfig robotConfig;

    private Boolean config = false;

    //@Value("${yeyu.flashPicSwitch}")
    private Boolean flashPicSwitch;

    // @Value("${yeyu.goBackcSwitch}")
    private Boolean goBackcSwitch;

    // @Value("${yeyu.groupManger}")
    private List<String> groupManger;

    //@Value("${yeyu.addFrendSwitch}")
    private Boolean addFrendSwitch;

    // @Value("${yeyu.addGroupSwitch}")
    private Boolean addGroupSwitch;


    private String robotQQ;

    private String owners;

    private String blackWord;

    private String saveConfigPath;


    private String sessionKey;


    public String getSessionKey() {
        return sessionKey;
    }

    public void setSessionKey(String sessionKey) {
        this.sessionKey = sessionKey;
    }

    //@Value("${yeyu.host}")
    private String host;
    // @Value("${yeyu.port}")
    private String port;
    // @Value("${yeyu.token}")
    private String token;


    /*mirai config start*/

    private void miraiConfig() {
        //TODO 测试
//        if (1 == 1) {
//            sessionKey = "vvS5hxPu";
//            return;
//        }


        try {
            //http://localhost:8082/verify
            MediaType JSON = MediaType.parse("application/json; charset=utf-8");
            RequestBody body = RequestBody.create(JSON, String.format("{\"verifyKey\":%s}", token));

            String resp = HttpUtil.synHttpPost(getRobotUrl() + "/verify", body);
            JsonObject root = MyQQUtil.getRoot(resp);


            String session = root.get("session").getAsString();
            sessionKey = session;
            log.info("session:{}", session);
            body = RequestBody.create(JSON, String.format("{\"sessionKey\": \"%s\",\"qq\": %s}",
                    session, robotQQ));
            String resp1 = HttpUtil.synHttpPost(getRobotUrl() + "/bind", body);
            log.info("bind:{}", resp1);
        } catch (Exception e) {
            e.printStackTrace();
        }
        ///release 释放

    }

    /*mirai config end*/
    public void setSaveConfigPath(String saveConfigPath) {
        this.saveConfigPath = saveConfigPath;
    }

    public String getSaveConfigPath() {
        return saveConfigPath;
    }

    public Boolean getConfig() {
        return config;
    }

    public void setConfig(Boolean config) {
        this.config = config;
    }

    public String getOwners() {
        return owners;
    }

    public void setOwners(String owners) {
        this.owners = owners;
    }

    public String getHost() {
        return host;
    }


    public void setBlackWord(String blackWord) {
        this.blackWord = blackWord;
    }

    public String getBlackWord() {
        return blackWord;
    }

    public void setHost(String host) {
        this.host = host;
    }

    public String getPort() {
        return port;
    }

    public void setPort(String port) {
        this.port = port;
    }

    public String getToken() {
        return token;
    }

    public void setToken(String token) {
        this.token = token;
    }

    public void setRobotQQ(String robotQQ) {
        this.robotQQ = robotQQ;
    }

    public String getRobotQQ() {
        return robotQQ;
    }

    public Boolean getFlashPicSwitch() {
        return flashPicSwitch;
    }

    public void setFlashPicSwitch(Boolean flashPicSwitch) {
        this.flashPicSwitch = flashPicSwitch;
    }

    public Boolean getGoBackcSwitch() {
        return goBackcSwitch;
    }

    public void setGoBackcSwitch(Boolean goBackcSwitch) {
        this.goBackcSwitch = goBackcSwitch;
    }

    public List<String> getGroupManger() {
        return groupManger;
    }

    public void setGroupManger(List<String> groupManger) {
        this.groupManger = groupManger;
    }

    public Boolean getAddFrendSwitch() {
        return addFrendSwitch;
    }

    public void setAddFrendSwitch(Boolean addFrendSwitch) {
        this.addFrendSwitch = addFrendSwitch;
    }

    public Boolean getAddGroupSwitch() {
        return addGroupSwitch;
    }

    public void setAddGroupSwitch(Boolean addGroupSwitch) {
        this.addGroupSwitch = addGroupSwitch;
    }

    public boolean delGroup(String group) {
        int index = -1;
        for (int i = 0; i < groupManger.size(); i++) {
            if (groupManger.get(i).trim().equals(group)) {
                index = i;
                break;
            }
        }
        if (index != -1) {
            groupManger.remove(index);
            return true;
        } else {
            return false;
        }
    }

    public boolean containGid(String mqFromid) {
        for (int i = 0; i < groupManger.size(); i++) {
            if (groupManger.get(i).trim().equals(mqFromid)) {
                return true;
            }
        }
        return false;
    }


    public boolean containBlackWord(String word) {
        String[] bws = blackWord.split("\\|");
        for (int i = 0; i < bws.length; i++) {
            if (word.contains(bws[i])) {
                return true;
            }
        }
        return false;
    }


    @Override
    public String toString() {
        return "RobotConfig{" +
                //"robotConfig=" + robotConfig +
                ", config=" + config +
                ", flashPicSwitch=" + flashPicSwitch +
                ", goBackcSwitch=" + goBackcSwitch +
                ", groupManger=" + groupManger +
                ", addFrendSwitch=" + addFrendSwitch +
                ", addGroupSwitch=" + addGroupSwitch +
                ", robotQQ='" + robotQQ + '\'' +
                ", owners='" + owners + '\'' +
                ", blackWord='" + blackWord + '\'' +
                ", host='" + host + '\'' +
                ", port='" + port + '\'' +
                ", token='" + token + '\'' +
                '}';
    }

    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }

//    public void change(RobotConfig cfg) {
//        BeanUtils.copyProperties(cfg, robotConfig);
//    }

    @PostConstruct
    public void readConfig() {

        // return;
        log.info("正在读取配置....{}", robotConfig);
        File file = new File(saveConfigPath);
        if (!file.exists()) {
            log.error(file + " Not Found.");
        } else {
            try {
                InputStream in = new FileInputStream(file);
                byte jsonByte[] = new byte[in.available()];
                in.read(jsonByte);
                String json = new String(jsonByte, StandardCharsets.UTF_8);
                RobotConfig rcf = new Gson().fromJson(json, RobotConfig.class);
                rcf.setConfig(true);
                log.info("配置读取完成:{}", rcf);
                // change(rcf);
                BeanUtils.copyProperties(rcf, robotConfig);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        miraiConfig();
    }

    /**
     * 机器人请求地址
     * @return
     */
    public String getRobotUrl() {
        return "http://" + host + ":" + port;
    }

}
